package com.wp.targetOffer;

import java.util.ArrayList;

/**
 * Created by 王萍 on 2017/8/14 0014.
 */

/**
 * 输入一颗二叉树和一个整数，打印出二叉树中结点值的和为输入整数的所有路径。
 * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 */
public class 二叉树中和为某一值的路径 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);

        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node6;
        node3.left = node5;
        node3.right = node7;

        ArrayList<ArrayList<Integer>> arrayLists = FindPath(node1, 9);
        arrayLists.stream().forEach(x -> {
            x.stream().forEach(node -> System.out.print(node + " "));
            System.out.println();
        });
    }

    private static ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();    //记录所有的满足条件的路径
    private static ArrayList<Integer> list = new ArrayList<>();                        //记录当前遍历的路径。

    public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
        if (root == null) return listAll;
        target -= root.val;
        list.add(root.val);
        if (target == 0 && isLeafNode(root)) listAll.add(new ArrayList<>(list));
        FindPath(root.left, target);
        FindPath(root.right, target);
        //当前节点及其子节点遍历完后，需要从list中删除
        //相当于深度遍历完一条路径后往回退了一步。
        list.remove(list.size() - 1);
        return listAll;
    }

    public static boolean isLeafNode(TreeNode root) {
        return root.left == null && root.right == null;
    }

    private static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }
}
